package com.xzixi.websocket.interceptablewebsocketdemo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.messaging.support.GenericMessage;

import java.nio.charset.StandardCharsets;

/**
 * @author 薛凌康
 */
public class GenericMessageBuilder {

    private Object payload;
    private MessageHeadersBuilder headersBuilder = new MessageHeadersBuilder();

    public GenericMessageBuilder payload(Object payload) {
        this.payload = payload;
        return this;
    }

    public GenericMessageBuilder destination(String destination) {
        this.headersBuilder.destination(destination);
        return this;
    }

    public GenericMessageBuilder leaveMutable(boolean leaveMutable) {
        this.headersBuilder.leaveMutable(leaveMutable);
        return this;
    }

    public GenericMessage<byte[]> build() {
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsString(payload).getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new GenericMessage<>(bytes, this.headersBuilder.build());
    }

}
